using System;
using System.Web.UI.WebControls;

using Impact.Controllers;
using Impact.Infrastructure.Exceptions;
using Impact.Model.Objects;
using Impact.Web.Foundation;
using System.Text.RegularExpressions;

namespace Impact.Web.Controls
{
    /// <summary>
    /// code-behind for the comments editor control
    /// </summary>
    public partial class CommentEditor : Impact.Web.Foundation.UserControlBase
    {

        /// <summary>
        /// checks for required parameters 
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Check.Require(articleId > 0, "ArticleID must be set before the control can load");
        }


        private int articleId;

        /// <summary>
        /// gets or sets the ID of the article that this comment will be posted to
        /// </summary>
        public int ArticleId
        {
            get { return articleId; }
            set { articleId = value; }
        }


        /// <summary>
        /// event handler for the submit button
        /// </summary>
        protected void CommentSubmitCommand(object sender, CommandEventArgs e)
        {
            if (Page.IsValid)
            {
                string text = body.Text;
                text = Regex.Replace(text, @"<(.|\n)*?>", string.Empty); // strip HTML
                text = text.Replace("\n", "<br/>");

                ArticleComment comment = new ArticleComment();
                comment.Author = name.Text;
                comment.AuthorUrl = website.Text;
                comment.Body = text;
                comment.ArticleId = articleId;
                ArticleController.SaveArticleComment(comment, Request.UserHostAddress);

                Reload();

            }
        }
    }
}